import { ForbiddenException, Injectable, UnauthorizedException } from '@nestjs/common'
import { UserService } from '../user/user.service'
import { JwtService } from '@nestjs/jwt'
import * as argon2 from 'argon2'

@Injectable()
export class AuthService {
  constructor(
    private UserService: UserService,
    private jwt: JwtService
  ) {}
  //登录
  async signin(username: string, password: string) {
    // console.log('🚀 ~ AuthService ~ signin ~ username:', username)
    // 通过username查找用户
    const user = await this.UserService.find(username)
    // console.log('🚀 ~ AuthService ~ signin ~ user:', user)
    if (!user) {
      throw new ForbiddenException('用户不存在，请注册')
    }
    // argon2用户密码进行对比
    const isPasswordValid = await argon2.verify(user.password, password)
    if (!isPasswordValid) {
      throw new ForbiddenException('用户名或密码错误') //不能确定哪个，否则给破解人一个准确的目标了
    }
    // 生成token
    return await this.jwt.signAsync({
      username: user.username,
      sub: user.id
    })
    // if (user && user.password === password) {
    //   // 生成token
    //   return await this.jwt.signAsync(
    //     {
    //       username: user.username,
    //       sub: user.id
    //     }
    //     // 这里是局部设置=>refreshToken(刷新token)
    //     // {
    //     //   expiresIn: 'id'
    //     // }
    //   )
    // }
    // 返回错误信息
    // throw new UnauthorizedException() //sign => service => jwtService
  }
  //   注册
  async signup(username: string, password: string) {
    // 注册接口说白了就是创建一个用户：提供username+password即可
    const user = await this.UserService.find(username)
    if (user) {
      throw new ForbiddenException('用户已存在')
    }
    const res = await this.UserService.create({ username, password })
    // console.log('🚀 ~ AuthService ~ signup ~ res:', res)
    return res
  }
}
